$(document).ready(function(){
	MC.ProfileModel = Backbone.Model.extend({
		defaults: {
			'name': '',
			'dob': '',
			'address1': '',
			'address2': '',
			'postal_code': '',
			'mobile': '',
			'email': ''
		}
	});
	MC.profileModel = new MC.ProfileModel();
	
	MC.CardModel = Backbone.Model.extend();
	
	MC.CardCollection = Backbone.Collection.extend({
		model: MC.CardModel
	});
	MC.cardCollection = new MC.CardCollection();
	
	MC.ProfileView = Backbone.View.extend({
		el: "#profile-tbl",
		
		template: _.template($('#profile-tpl').html()),
		
		initialize: function(){
			_.bindAll(this, 'render');
			MC.profileModel.on('change', this.render);
			
		},
		
		render: function(){
			console.log($('#profile-tpl').html());
			$(this.el).html(this.template(MC.profileModel.toJSON()));
			console.log(MC.profileModel.toJSON());
			return this;
		}
	});
	
	MC.CardView = Backbone.View.extend({
		tagName: 'tr',
		
		template: _.template($('#card-tpl').html()),
		
		initialize: function() {
			_.bindAll(this, 'render');
			var expiryDate = new Date(this.model.get('expiryDate'));
		},
		render: function() {
			$(this.el).html(this.template(this.model.toJSON()));
			return this;
		}
	});
	
	MC.CardCollectionView = Backbone.View.extend({
		el: '#cards',
		
		initialize: function() {
			_.bindAll(this, 'render', 'addOne');
			MC.cardCollection.on('reset', this.render);
			MC.cardCollection.on('add', this.addOne);
		},
		
		render: function(){
			$(this.el).html($('#card-header-tpl').html());
			var $this = this;
			_.each(MC.cardCollection.models, function(model){
				$this.addOne(model);
			});
			$(this.el).append($('#card-footer-tpl').html());
			return this;
		},
		
		addOne: function(model) {
			var cardView = new MC.CardView({model: model});
			$(this.el).append(cardView.render().el);
		}
	});
	
	
	MC.ProfileAppView = Backbone.View.extend({
		el: "#body",
		render: function() {
			MC.profileView = new MC.ProfileView();
			this.$('#profile-tbl').html(MC.profileView.render().el);
			
			MC.cardCollectionView = new MC.CardCollectionView();
			this.$('#profile-tbl').html(MC.cardCollectionView.render().el);
			return this;
		}
	});
	MC.profileAppView = new MC.ProfileAppView();
	MC.profileAppView.render();
	
	// update profile model
	$.get('/mpems/profile/getProfile', function(data){
		MC.profileModel.set(data);
		console.log(MC.profileModel);
	});
	
	$.get('/mpems/profile/getAllCards/', function(data){
		MC.cardCollection.reset(data);
	});

});